<?php

namespace yphp;

/**
 * 文件处理类
 */
class DealFile extends Instance
{
    // 复制文件
    static function copy($source, $target, $force = false)
    {
        self::createDir(dirname($target));
        if ($force || !is_file($target)) copy($source, $target);
    }

    // 创建目录
    static function createDir($path)
    {
        is_dir($path) || mkdir($path, 0777, true);
    }

    // 写入文件
    static function writeFile($path, $content = '', $force = false)
    {
        self::createDir(dirname($path));
        if ($force || !is_file($path)) {
            file_put_contents($path, $content, LOCK_EX);
        }
    }

    // 删除目录
    static function delDir($dir, $un_null = false)
    {
        if (is_dir($dir)) {
            $d = dir($dir);
            while (false !== ($path = $d->read())) {
                if ($path === '.' || $path === '..') continue;
                self::delDir($dir . DS . $path, $un_null);
            }
            $d->close();
            @rmdir($dir);
        } elseif ($un_null && is_file($dir)) {
            unlink($dir);
        }
    }

    // 判断缓存文件是否有效
    static function cacheFile($file, $time)
    {
        return $time > 0 && is_file($file) && (YP_START - filemtime($file) < $time);
    }

    // 目录及文件详情
    static function lists($path)
    {
        $list = ['path' => $path];
        if (is_dir($path)) {
            $list['type'] = 'dir';
            $size = 0;
            $down = [];
            $dir = dir($path);
            while (false !== ($p = $dir->read())) {
                if ($p === '.' || $p === '..') continue;
                $l = self::lists($path . DS . $p);
                $size += $l['size'];
                $down[] = $l;
            }
            $dir->close();
            $list['size'] = $size;
            $list['down'] = $down;
        } elseif (is_file($path)) {
            $list['type'] = 'file';
            $list['size'] = filesize($path);
        } else {
            throw new \Exception('路径' . $path . '异常');
        }
        return $list;
    }

    // 内容追加
    function append($path,$content)
    {
        self::createDir(dirname($path));

        file_put_contents($path, $content, FILE_APPEND);
    }
}